<template>
  <u-navbar title="发布帖子" leftIcon="arrow-left" :autoBack="true" :placeholder="true">
    <template #right>
      <view
        class="postBtn orangeBg"
        v-if="form?.content?.length > 0 || form.title?.length > 0 || form?.imgList?.length > 0"
        @click="toSubmit"
        >发布</view
      >
      <view class="postBtn " v-else>发布</view>
    </template>
  </u-navbar>
  <view class="content">
    <view class="trendsTitle">
      <view class="inputBox">
        <input
          type="text"
          placeholder="请输入标题（非必填)"
          v-model.trim="form.title"
          placeholder-style="color:#bcbcbc"
          autofocus
          :focus="focus"
        />
      </view>
    </view>

    <view style="padding: 0 ">
      <textarea
        v-model.trim="form.content"
        maxlength="200"
        auto-height
        placeholder="写些什么和大家分享一下吧~"
        placeholder-style="color:#bcbcbc"
      />
      <view class="upload-img">
        <view class="img_list" @click="openAuth" v-show="form?.imgList?.length < 9">
          <image src="https://ossresource.miyingbl.com/def/26ee7202406141623554822.png" class="plus-icon"></image>
          <view style="color: #AAA; font-size: 24rpx;" class='u-p-t-10'>上传照片</view>
        </view>
        <view class="img_list" v-for="(item, index) in form.imgList" :key="index">
          <view class="img_list_del" @click="toDelete(index)">
            <u-icon name="https://ossresource.miyingbl.com/def/15eb5202406141627352507.png"  size="40rpx"></u-icon>
          </view>
          <image :src="item" mode="aspectFill" @click="previewImg(form.imgList, index)"></image>
        </view>
      </view>
    </view>
  </view>
  <h-authpup
    ref="authpup"
    :h="system.statusHeight"
    type="top"
    @changeAuth="changeAuth"
    permissionID="CAMERA"
  ></h-authpup>

  <u-action-sheet
    :actions="sheetList"
    :closeOnClickOverlay="true"
    :closeOnClickAction="true"
    @select="selectClick"
    description="您将退出编辑，是否要保存草稿？"
    :show="showSheet"
    :safeAreaInsetBottom="true"
    cancelText="取消"
    @close="closeSheet"
    round="30"
  ></u-action-sheet>

  <view class="fixBottom">
    <!-- <picker @change="bindPickerChange" :value="tabIndex" :range="tabList">

      </picker> -->
    <u-picker
      :show="showCate"
      :columns="tabList"
      confirmColor="#26c6cb"
      @confirm="confirmCate"
      @cancel="showCate = false"
    ></u-picker>
    <view class="select" @click="showCate = true">
      <image
        src="https://ossresource.miyingbl.com/def/0385c20240523154216788.png"
        mode=""
      >
      </image>
      <view class="title">选择标签</view>
      <view v-if="tabIndex != null">{{ navList[tabIndex].title }}</view>
      <image
        src="https://ossresource.miyingbl.com/def/8481b202405231405407334.png"
        size="16"
        class="arrowRight"
      ></image>
    </view>
    <view class="select" @click="navigateTo('/socials/drafts/drafts')">
      <image src="https://ossresource.miyingbl.com/def/4fab0202405231611432078.png" mode="">
      </image>
      <view class="title">草稿箱</view>
      <view>草稿({{ countDrafts }})</view>
      <image
        src="https://ossresource.miyingbl.com/def/8481b202405231405407334.png"
        size="16"
        class="arrowRight"
      ></image>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick, computed, watch } from 'vue'
import { navigateTo, showToast, navigateBack ,redirectTo} from '@/utils'
import {
  onLoad,
  onPullDownRefresh,
  onReachBottom,
  onUnload,
  onBackPress,
  onReady,
  onShow,
} from '@dcloudio/uni-app'
import { socialTopicPublish, socialLabelList ,CoupeDraftsAddApi,CoupeDraftsApi,CoupeDraftsEditApi,coupeDetailsApi} from '@/api/social'
import { uploadApi } from '@/utils/upLoad'
import { useMemberStore, useSystemStore } from '@/stores'
import {
  trendsCateList, //动态分类
  trendsDraftsAdd, //草稿箱
  trendsDraftsList, //草稿箱列表
  trendsDraftsDel, //草稿箱删除
} from '@/api/trends'
const userStore = useMemberStore()
const token = userStore?.token
const userInfo = ref(userStore.userInfo)
const system = useSystemStore()
const showCate = ref(false)
const authpup = ref(null)
const showSheet = ref(false)
const uploadFlag = ref(true)
onShow(async () => {
  let res = await CoupeDraftsApi({type:1})
  if (res) {
    countDrafts.value = res.data.total
  }
})
onUnload(() => {
  // uni.$off('editDrafts')
  uni.removeStorage({
      key:'editDrafts',
      success: function(res){
          console.log('删除成功')
      }
  })
})
const sheetList = ref([
  {
    name: '保存草稿',
  },
  {
    name: '不保存',
  },
])
onReady(() => {
  // #ifdef APP-PLUS || APP-IOS || APP-ANDROID
  uni.showKeyboard()
  // #endif
})
const leftClick = () => {
  showSheet.value = true
}

const selectClick = async (e) => {
  if (e.name == '保存草稿') {
    let res = await savetrendsDrafts()
    uni.hideLoading({ noConflict: true })
    if (res.code == 200) {
      flag.value = false
      navigateBack()
    }
    showToast(res.message)
  } else {
    flag.value = false
    navigateBack()
  }
}
onBackPress(({ from }) => {
  if (flag.value) {
    showSheet.value = true
    return true
  } else {
    return false
  }
})
const focus = ref(true)
const closeSheet = () => {
  showSheet.value = false
}

function openAuth() {
  nextTick(() => {
    authpup.value.open()
  })
}

function changeAuth() {
  if(!uploadFlag.value) return
  uploadFlag.value=false
  uni.chooseImage({
    count: 9 - form.value?.imgList?.length, //默认9
    sizeType: ['compressed'],
    success: async (e) => {
      select(e)
    },
  })
}

var form = ref({
  content: '',
  imgList: [],
  label_id: '',
})
var type = ref(0)
var tabIndex = ref(null)
var tabList = ref([])
var navList = ref([])
const countDrafts = ref(0)
const DraftsId = ref(null)
const editsId = ref(null)
const postType=ref(1)
onLoad(async (options) => {
  let res = await getLabel()
  let editDrafts = uni.getStorageSync('editDrafts');
  if(options.type){
    postType.value=options.type
  }
  // 草稿箱
  if(editDrafts){
    let item=editDrafts
    console.log(item)
      DraftsId.value = item.id
      form.value = item
      form.value.imgList = form.value?.link_url?.length > 0 ? form.value.link_url : []
      form.value.label_id = form.value?.tag
      flag.value = true

      if (item.tag) {
        tabIndex.value = navList.value.findIndex((v) => v.id == item.tag)
        console.log(tabIndex.value)
      }
    }
    // 编辑获取信息
  if(options?.id){
    editsId.value=options?.id
    let result = await coupeDetailsApi({  article_id: options.id,  type:1})
    form.value = result.data
    form.value.imgList = form.value?.link_url?.length > 0 ? form.value.link_url : []
    form.value.label_id = form.value?.category
    if (form.value?.category) {
      console.log(navList.value)
      tabIndex.value = navList.value.findIndex((v) => v.id == form.value?.category)
      console.log(tabIndex.value)
    }
  }
})

function previewImg(list, index) {
  uni.previewImage({
    urls: list,
    current: index,
    fail: (err) => {
      console.log(err)
    },
  })
}

function toBack() {
  uni.navigateBack({
    delta: 1,
  })
}
async function toSubmit() {
  const system = useSystemStore()
  uni.showLoading({
    title: '发布中',
  })
  if (tabIndex.value == null) {
    uni.showToast({
      title: '请选择标签',
      icon: 'error',
    })
    uni.hideLoading()
    return false
  }
  // if (!form.value.content) {
  //   uni.showToast({
  //     title: '请输入内容',
  //     icon: 'error',
  //   })
  //   uni.hideLoading()
  //   return false
  // }
  let data = {
    category: form.value.label_id,
    content: form.value.content,
    province: system?.location?.province || '',
    city: system?.location?.city || '',
    title: form.value.title,
  }
   if (DraftsId.value) {
     data.caogao_id=DraftsId.value
   }
  if (form.value?.imgList?.length > 0) {
    data.images = form.value.imgList.toString()
  }
  if(editsId.value){
    data.id=editsId.value
  }

  const res = await socialTopicPublish(data)
  uni.hideLoading({ noConflict: true })
  if (res.code == 200) {
    flag.value = false
    console.log(userInfo)
    // navigateBack()
    redirectTo('/socials/content/content?type=1')
    // if (DraftsId.value) {
    //   trendsDraftsDel({ id: DraftsId.value })
    // }
  }
  showToast(res.message)
}
const flag = ref(false)
watch(form.value, (nval) => {
  if (form.value?.title?.length > 0 || form.value?.content?.length > 0) {
    flag.value = true
  } else {
    flag.value = false
  }
})

async function getLabel() {
  const userStore = useMemberStore()
  const token = userStore?.token
  // let identity
  // if (token) {
  //   // 登录后用返回的
  //   identity =
  //     userStore?.userInfo?.user.identity_status || userStore?.casualUser?.identity_status || 0
  // } else {
  //   // 没登录用存本地
  //   identity = userStore?.casualUser?.identity_status || 0
  // }
  const res = await socialLabelList()
  // let res ={
  //   data: [
  //     {name:'分类',id:1}
  //   ]
  // }
  var list = res.data.map((v) => {
    return v.title
  })

  tabList.value.push(list)
  navList.value = res.data
  return res.data
}

async function select(evt) {
  var list = evt.tempFilePaths
  var num = 5 * 1024 * 1024
  for (var i in list) {
    if (list[i].size > num) {
      var a = Number(i) + 1
      uni.showToast({
        title: '第' + a + '张图片上传失败',
        icon: 'none',
        duration: 2000,
      })
      continue
    }
    uni.showLoading({
      title: '上传中...',
    })
    const res = await uploadApi(list[i])
    form.value.imgList.push(res)
    uni.hideLoading()
    if(i==list.length-1){
      uploadFlag.value=true
    }
  }
}

function bindPickerChange(e) {
  tabIndex.value = e.detail.value
  form.value.label_id = navList.value[e.detail.value].id
}

function toDelete(index) {
  form.value.imgList.splice(index, 1)
}
// 记录地点， 打开地图选择位置
function chooseLocationFn() {
  uni.chooseLocation({
    success: function (res) {
      form.value.address = res.address
      form.value.lat = res.latitude
      form.value.lon = res.longitude
    },
  })
}
const inputBindFocus = (e) => {
  console.log(e)
}

const confirmCate = (e) => {
  tabIndex.value = e.indexs[0]

  form.value.label_id = navList.value[tabIndex.value].id
  // tabName.value=e.indexs[0]
  showCate.value = false
}
const savetrendsDrafts = async () => {
  let data = {type:1}
  if (tabIndex.value) {
    data.tag = form.value.label_id
  }
  if (form.value?.content?.length > 0) {
    data.content = form.value.content
  }
  if (form.value?.imgList?.length > 0) {
    data.link_url = form.value.imgList
  }
  if (form.value?.title?.length > 0) {
    data.title = form.value.title
  }
  if (DraftsId.value) {
    data.id = DraftsId.value
     const res = await CoupeDraftsEditApi(data)
      return res
  }else{
    const res = await CoupeDraftsAddApi(data)
     return res
  }

}
</script>
<style>
page {
  background: #fff;
  font-family: PingFangSC, PingFang SC;
}
</style>
<style lang="scss" scoped>
.img_list {
  width: 200rpx;
  height: 200rpx;
  float: left;
  position: relative;
  border-radius: 10rpx;
  margin-right: 20rpx;
  margin-bottom: 10rpx;
  background: #f6f6f6;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  &:nth-child(3n + 3) {
    margin-right: 0;
  }
  image {
    width: 100%;
    height: 100%;
    border-radius: 10rpx;
  }
  .plus-icon{
    width:50rpx;
    height:50rpx;
    display:block;
  }

  .img_list_del {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    z-index: 1;
  }
}

.postBtn {
  width: 108rpx;
  line-height: 48rpx;
  height: 48rpx;
  background: #d9d9d9;
  text-align: center;
  border-radius: 24rpx 24rpx 24rpx 24rpx;
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 30rpx;
  color: #ffffff;

  &.pinkBg {
    background: #ff85a3;
  }

  &.orangeBg {
    background: #00C1B9;
  }

  &.blueBg {
    background: #26c6cb;
  }
}

.upload-img {
  margin-top: 30rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
}

textarea {
  width: 100%;
  min-height: 200rpx;
  padding-top: 30rpx;
  font-size: 26rpx;
}

.upContent {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
}

.upContent-left {
  font-size: 28rpx;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  color: #000000;
}

.upContent-right {
  display: flex;
  align-items: center;
}

.upContent-mmolle {
  font-size: 26rpx;
  font-family: PingFang SC;
  font-weight: 500;
  color: #999;
  margin-right: 14rpx;

  text {
    margin-left: 10rpx;
  }
}

.upContent-right_img {
  width: 32rpx;
  height: 32rpx;
}

.content {
  // border-top: 1px solid #e9e9e9;
  padding: 0 24rpx;
}

.title {
}

.select {
  font-weight: 500;
  font-size: 26rpx;
  color: #202020;
  height: 88rpx;
  background: #f6f6f6;
  border-radius: 10rpx 10rpx 10rpx 10rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  margin-top: 10rpx;

  image {
    width: 30rpx;
    height: 30rpx;
    display: block;
  }
  .arrowRight {
    width: 26rpx;
    height: 26rpx;
    display: block;
    margin-left: 15rpx;
  }
  .title {
    padding-left: 11rpx;
    flex: 1;
  }
}

.fixBottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 24rpx 15rpx;
  padding-bottom: calc(15rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(15rpx + env(safe-area-inset-bottom));
  // box-shadow: 0rpx -4rpx 16rpx -4rpx rgba(190, 190, 190, 0.25);
  background: #fff;
  z-index: 99;
}

.trendsTitle {
  border-bottom: 1px solid #e1e1e1;
  padding: 30rpx 0;
  display: flex;
  align-items: center;

  .icon {
    width: 34rpx;
    height: 34rpx;
    display: block;
    margin-right: 10rpx;
  }

  .inputBox {
    flex: 1;
    font-size: 24rpx;
  }
}

</style>
